import time

from selenium import webdriver
from selenium.common import InvalidArgumentException, WebDriverException, NoSuchElementException
from selenium.webdriver.common.by import By


class Base:
    def __init__(self, browser):
        # 打开浏览器,设置driver
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None
    def get(self, url):
        #请求目标网址
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('输入的地址不正确')
    def find_element(self, locator):  #locator = (By.xx, value) 元组
        # 定位元素
        try:
            ele = self.driver.find_element(*locator)    #拆包*locator = (By.xx, value)
            # print(ele.get_attribute("outerHTML"))
            return ele
        except NoSuchElementException:
            print('元素定位失败')
    def click(self, locator):
        # 元素点击操作
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('元素定位失败')
    def get_attribute(self, locator):
        element = self.find_element(locator)
        print(element.get_attribute("outerHTML"))

    def send_keys(self, locator, text):
        element = self.find_element(locator)
        if element is not None:
            element.send_keys(text)
        else:
            print('元素定位失败')

    def quit(self, seconds):
        # 输入文本
        time.sleep(seconds)
        self.driver.quit()
    def back(self):
        # 后退
        self.driver.back()
    def forward(self):
        # 前进
        self.driver.forward()
    def refresh(self):
        # 刷新
        self.driver.refresh()
if __name__ == '__main__':
    bs = Base('chrome')
    bs.get("https://www.so.com/")
    bs.find_element((By.ID, "input"))
    bs.get_attribute((By.ID, "input"))
    bs.send_keys((By.ID, "input"), "沁阳天气")
    bs.click((By.ID, "search-button"))
    bs.back()
    time.sleep(2)
    bs.forward()
    time.sleep(2)
    bs.refresh()
    time.sleep(3)
    bs.quit(3)
